package com.lqq.chapter02.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lqq677
 * @Date 2021/8/9 10:07
 * @Description 在高内聚低耦合前提下：线程  操作(对外暴露的调用方法)  资源类
 *  3个售票员卖30张票
 */



//第一步 创建资源类，定义属性和操作方法
class LTicket {
    //可重入锁
    //private Lock lock = new ReentrantLock();//非公平锁
    private Lock lock = new ReentrantLock(true);//公平锁
    //票数(资源)
    private Integer ticket = 30;
    //操作方法：卖票
    public void sale() {
        //获取锁
         lock.lock();
                 try {
                     //判断是否有票
                     if (ticket > 0) {
                         System.out.println(Thread.currentThread().getName() + "卖出" + (ticket--) + "，剩余" + ticket);
                     }
                 }catch (Exception e){
                     e.printStackTrace();
                 }finally {
                     //解锁
                     lock.unlock();
                 }
    }

}

public class LSaleTicket {
    //第二步 创建多个线程，调用资源类的操作方法
    public static void main(String[] args) {

        //创建Ticket对象(资源)
        LTicket ticket = new LTicket();

        //3个(售票员)线程
        new Thread(()-> {for (int i = 0; i < 40; i++) ticket.sale(); }, "AA").start();
        new Thread(()-> {for (int i = 0; i < 40; i++) ticket.sale(); }, "BB").start();
        new Thread(()-> {for (int i = 0; i < 40; i++) ticket.sale(); }, "CC").start();

    }
}
